<?php
/**
 * 图片画册
 * AUTHOR  : zlf
 * DateTime: 2022/06/18 09:00
 */
namespace App\V3\V3_1\Controllers;

use Illuminate\Http\Request;
use App\V3\V3_1\Services\TextImageTemplatesService;
use Illuminate\Support\Facades\Validator;
use App\V3\V3_1\Models\TextImageTemplatesModel;
use OSS\OssClient;
use Illuminate\Support\Facades\DB;
use App\V3\V3_1\Models\AdminAddendumModel;

class TextImageTemplatesController extends BaseController
{
    protected $ossClient;
    public function __construct(Request $request){
        parent::__construct($request);
        $this->ossClient=new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
            );
    }
   /**
     * 添加模板
     *
     * @param temp_title        模板标题
     * @param temp_color        模板颜色
     * @param temp_number       模板序号
     * @param temp_content1     模板内容1
     * @param temp_content2     模板内容2
     * @param h5_temp_id        H5模板id
     * @param pa_id             文字图片画册id
     * @param temp_img_video_01 模板素材图片/视频 1
     * @param temp_img_video_02 模板素材图片/视频 2
     * @param temp_type         模板类型：1、单图/单视频  2、多图/多视频 3、背景模板 4、首页封面模板
     */
     public function addContentTempLate(Request $request){
         $adminInfo   = AdminAddendumModel::select('is_vip')->where(['main_id'=>$this->getMainUserId()])->first()->toArray();

         if(!empty($adminInfo) && in_array($adminInfo['is_vip'],[1,2])){
             /*
              if($adminInfo['one_key_album_times'] != -1 && $total_num >= $adminInfo['one_key_album_times']){

              return $this->fail('','您一键生成商品画册次数，已达到设置数量！');
              }

              if($adminInfo['album_amount'] != -1 && $total_num >= $adminInfo['album_amount']){

              return $this->fail('','您生成商品画册彩页，已达到设置数量！');
              } */

         }else{

             return $this->fail('','您还不是VIP会员，还不能创建文字画册模板！');
         }
        $tInfo = TextImageTemplatesModel::where(['pa_id'=>$request->pa_id,'temp_type'=>4,"temp_tags_id"=>$request->temp_tags_id])->first();  
        if(!empty($tInfo)){
            return $this->fail('','首页封面模板，已存在');
        }
        DB::beginTransaction();
        try {
            
        $data = self::handlePostData($this->ossClient,$request,$this->getMainUserId());//处理Post请求的数据包
        if ($data['code'] === 0){
            $data            = $data['data'];
            $data['user_id'] = $this->getUserId();
            if($data['temp_type'] == 4) $data['is_top']=1;
            $res=TextImageTemplatesService::addContentTempLate($data);
            if($res['code']===0){
                $this->log('文字画册内容模板,添加成功', $res);
            }
            DB::commit();
            return response()->json($res);
        }else{
            return response()->json($data);
        }
        } catch (\Exception $e) {
            DB::rollBack();
            $this->fail('',$e->getMessage());
        }
    }

    /**
     * 删除模板
     *
     * @param t_id 模板id
     */
    public function delContentTempLate(Request $request){

        if(empty($request->input('t_id'))){

            return response()->json(['code'=>1,'msg'=>'缺必要参数，模板id','data'=>null]);
        }

        //$condition['user_id'] = $this->getUserId();
        $condition['id']      = $request->input('t_id');

        $info=TextImageTemplatesService::getTextImageTemplatesInfo($condition);

        if (empty($info)){

            return response()->json(['code'=>1,'msg'=>'请求不合法','data'=>null]);
        }
         //素材01,删除服务器中没有用的素材图片
        if(!empty($info['temp_img_video_01'])){

            $info['temp_img_video_01'] = explode(',',$info['temp_img_video_01']);

            foreach ($info['temp_img_video_01'] as $ivkey1=>$ivval1){

                //删除oss里的文件
                self::delOssFilePath($ivval1, $this->ossClient, $this->getMainUserId());
            }
        }

        //素材02,删除服务器中没有用的素材图片
        if(!empty($info['temp_img_video_02'])){

            $info['temp_img_video_02'] = explode(',',$info['temp_img_video_02']);

            foreach ($info['temp_img_video_02'] as $ivkey2=>$ivval2){

                //删除oss里的文件
                self::delOssFilePath($ivval2, $this->ossClient, $this->getMainUserId());
            }
        }

        $bool = TextImageTemplatesService::delContentTempLate($condition);

        if($bool){

            $this -> log('文字图片画册，删除成功', $bool);

            return response()->json(['code'=>0,'msg'=>'删除成功','data'=>null]);
        }

            return response()->json(['code'=>1,'msg'=>'删除失败','data'=>null]);
    }

    /**
     * 修改模板
     *
     * @param t_id              模板id
     * @param temp_title        模板标题
     * @param temp_color        模板颜色
     * @param temp_number       模板序号
     * @param temp_content1     模板内容1
     * @param temp_content2     模板内容2
     * @param h5_temp_id        H5模板id
     * @param pa_id             文字图片画册id
     * @param temp_img_video_01 模板素材图片/视频 1
     * @param temp_img_video_02 模板素材图片/视频 2
     * @param temp_type         模板类型：1、单图/单视频  2、多图/多视频 3、背景模板 4、首页封面模板
     */
    public function updateContentTempLate(Request $request){

        if(empty($request->input('t_id'))){

            return response()->json(['code'=>1,'msg'=>'缺必要参数，模板id','data'=>null]);
        }

        $data = self::handlePostData($this->ossClient,$request,$this->getMainUserId());//处理Post请求的数据包

        if ($data['code'] === 0){

            unset($data['data']['info']);
            $data['data']['user_id'] = $this->getUserId();
            $res = TextImageTemplatesService::updateContentTempLate($data['data']);

            if($res['code'] === 0){

                $this->log('文字图片画册，修改成功', $res);
            }

            return response()->json($res);
        }else{
            return response()->json($data);
        }
    }

    /**
     * 更换素材中某个的图片/视频
     *
     * @param t_id     素材id
     * @param old_path 原图片or视频路径
     * @param temp_img_video_01 模板素材图片/视频 1
     * @param temp_img_video_02 模板素材图片/视频 2
     */
    public function updMaterialImgVideo(Request $request){

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            't_id'     =>'required',
            'old_path' =>'required',
        ],
            [
            't_id.required'    => '缺必要参数，文字画册id',
            'old_path.required'=> '原图片or视频路径，不能为空'
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {

            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }

        //修改时，传递的内容模板id
        if(!empty($data['t_id'])){

            $condition['id'] = $data['t_id'];

            $info = TextImageTemplatesService::getTextImageTemplatesInfo($condition);

            if(!empty($info)){

                $data['info'] = $info;

            }else{

                return ['code' => 1,'msg'  => '内容模板不存在！','data' => ''];
            }
        }

            $flag = "temp_img_video_01";

        if(!empty($request->file("temp_img_video_02"))){

            $flag = "temp_img_video_02";
        }
        $data = self::handleUploadTempImageVideo($this->ossClient,$request, $data, $flag,$this->getMainUserId());

            if($data['code']===0){

             $file_path = $data[$data['m_flag']];

            return response()->json(['code'=>0,'msg'=>'更换成功','data'=>['new_path'=>$file_path]]);

        }else{


            return response()->json(['code'=>1,'msg'=>$data['msg'],'data'=>null]);
        }
    }

    /**
     * 查询模板列表
     *
     * @param pa_id     文字画册id
     * @param curr_page 页码
     */
    public function getContentTempLateList(Request $request){

        $adminInfo   = AdminAddendumModel::select('is_vip','album_page_amount')->where(['main_id'=>$this->getMainUserId()])->first()->toArray();

        if(!empty($adminInfo) && in_array($adminInfo['is_vip'],[1,2])){

            if($adminInfo['album_page_amount'] != -1 && $request->current_page >= $adminInfo['album_page_amount']){

                return response()->json([
                    'code' => 1,
                    'msg' => '您当前彩页超出限制'.$adminInfo['album_page_amount'].'页，超出部分未生成彩页',
                    'data' => '',
                ]);
            }
        }else{
            return response()->json([
                'code' => 1,
                'msg' => '您还不是VIP会员，不能展示彩页！',
                'data' => '',
            ]);
        }

        if(empty($request->input('pa_id'))){

            return response()->json(['code'=>1,'msg'=>'缺必要参数，文字画册id','data'=>null]);
        }

        //$condition['act.user_id'] = $this->getUserId();
        $condition['act.pa_id']   = $request->input('pa_id');

        $currentPage = !empty($request->input('curr_page'))?$request->input('curr_page'):1;
        $pageSize = !empty($request->input('page_size'))?$request->input('page_size'):20;
        $list        = TextImageTemplatesService::getContentTempLateList($condition, $currentPage,$pageSize);

        if(!empty($list['data'])){

            foreach ($list['data'] as $lk=>$lv){

                if (!empty($lv['temp_img_video_01'])){

                    $imgArr01 = explode(',',$lv['temp_img_video_01']);

                    foreach ($imgArr01 as $ik=>$iv){

                        $imgArr01[$ik]=self::addWatermark($this->ossClient,$iv,$this->getMainUserId());
                    }

                    $list['data'][$lk]['temp_img_video_01'] = $imgArr01;
                }

                if (!empty($lv['temp_img_video_02'])){

                    $imgArr02 = explode(',',$lv['temp_img_video_02']);

                    foreach ($imgArr02 as $ik=>$iv){

                        $imgArr02[$ik]=self::addWatermark($this->ossClient,$iv,$this->getMainUserId());
                    }

                    $list['data'][$lk]['temp_img_video_02'] = $imgArr02;
                }

                $list['data'][$lk]['create_time']=date('Y-m-d H:i:s', $lv['create_time']);
                $list['data'][$lk]['update_time']=date('Y-m-d H:i:s', $lv['update_time']);
            }
        }
        $this -> log('文字画册内容模板，查询成功', $list);

        return response()->json(['code'=>0,'msg'=>'查询成功','data'=>$list]);
    }

    /**
     * 查询模板信息
     *
     * @param t_id     内容模板id
     *
     */
    public function getContentTempLateInfo(Request $request){

        if(empty($request->input('t_id'))){

            return response()->json(['code'=>1,'msg'=>'缺必要参数，模板id','data'=>null]);
        }

        //$condition['user_id'] = $this->getUserId();
        $condition['id']      = $request->input('t_id');

        $info = TextImageTemplatesService::getTextImageTemplatesInfo($condition);

        if(!empty($info)){

            if (!empty($info['temp_img_video_01'])){

                $imgArr01 = explode(',',$info['temp_img_video_01']);

                foreach ($imgArr01 as $ik=>$iv){

                    $imgArr01[$ik]=self::addWatermark($this->ossClient,$iv,$this->getMainUserId());
                }

                $info['temp_img_video_01'] = $imgArr01;
            }

            if (!empty($info['temp_img_video_02'])){

                $imgArr02 = explode(',',$info['temp_img_video_02']);

                foreach ($imgArr02 as $ik=>$iv){

                    $imgArr02[$ik]=self::addWatermark($this->ossClient,$iv,$this->getMainUserId());
                }

                $info['temp_img_video_02'] = $imgArr02;
            }

            return response()->json(['code'=>0,'msg'=>'查询成功','data'=>$info]);

        }else{

            return response()->json(['code'=>1,'msg'=>'查询失败','data'=>null]);
        }
    }

    /**
     * 删除素材中的图片
     *
     * @param t_id        素材模板id
     * @param del_img_paths 删除原图片的路径
     * @param m_flag      删除原素材字段名
     */
    public function delMaterialImgVideo(Request $request){

        if(empty($request->input('t_id'))){

            return response()->json(['code'=>1,'msg'=>'缺必要参数，模板id','data'=>null]);
        }

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            't_id'        =>'required',
            'del_img_paths' =>'required',
            'm_flag'      =>'required'
        ],
            [
                't_id.required'          => '缺必要参数，模板id',
                'del_img_paths.required'   => '图片路径，不能为空',
                'm_flag.required'        => '素材标识，不能为空'
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return ['code' => 1,'msg'  => $info,'data' => ''];
        }

        $condition['id']      = $data['t_id'];
        //$condition['user_id'] = $this->getUserId();

        $info=TextImageTemplatesService::getTextImageTemplatesInfo($condition);

        if (empty($info)){

            return response()->json(['code'=>1,'msg'=>'内容模板不存在！','data'=>null]);
        }
        //删除服务器中没有用的素材图片
        if(!empty($info[$data['m_flag']])){

                $paths = "";

                $data['del_img_paths'] = explode(',',$data['del_img_paths']);
                $info[$data['m_flag']] = explode(',',$info[$data['m_flag']]);

                foreach ($info[$data['m_flag']] as $key=>$val){

                    if(in_array($val,$data['del_img_paths'])){
                        //删除oss里的文件
                        self::delOssFilePath($val, $this->ossClient, $this->getMainUserId());

                    }else{

                      $paths.=$val.',';
                    }
                }
                $updData[$data['m_flag']] = substr($paths,0,strrpos($paths,","));

                $bool = TextImageTemplatesModel::updateContentTempLate($condition,$updData);

                if($bool){

                    return ['code'=>0,'msg'=>'删除成功','data'=>$bool];

                }else{

                    return ['code'=>1,'msg'=>'删除失败','data'=>null];
                }
        }
    }

    /**
     * 处理Post请求的数据
     */
    static public function handlePostData($client,$request,$mainId){
        //参数验证
        $validator = Validator::make($data = $request->all(), [

            'pa_id'      =>'required',
            'temp_type'  =>'required',
        ],
        [
            'pa_id.required'       => '缺少参数，文字画册id',
            'temp_type.required'   => '缺少参数，模板类型'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return ['code' => 1,'msg'  => $info,'data' => ''];
        }

        $tinfo = [];

        //修改时，传递的内容模板id
        if(!empty($data['t_id'])){

            $condition['id'] = $data['t_id'];

            $tinfo = TextImageTemplatesService::getTextImageTemplatesInfo($condition);

            if(!empty($tinfo)){

            $data['info'] = $tinfo;

            }else{

                return ['code' => 1,'msg'  => '内容模板不存在！','data' => ''];
            }
        }
        $temp_info_data1 = self::updUploadTempImageVideo($client,$request,$data,'temp_img_video_01',$mainId);//处理上传素材的图片视频函数

        if ($temp_info_data1['code'] === 0){

            $data = $temp_info_data1['data'];

        }else{

            return $temp_info_data1;
        }
        if($data['temp_type'] == 2){//多图/多视频模板

            $temp_info_data2 = self::updUploadTempImageVideo($client,$request,$data,'temp_img_video_02',$mainId);//处理上传素材的图片视频函数

            if ($temp_info_data2['code'] === 0){

                $data = $temp_info_data2['data'];

            }else{
                return $temp_info_data2;
            }
        }
      return ['code' => 0,'msg'  => 'success','data' => $data];
    }


    /**
     * 处理上传素材的图片视频函数
     */
    static public function handleUploadTempImageVideo($client,$request,$fdata,$temp_img_video,$mainId){

        $data = [];
        $data[$temp_img_video] = '';

        //添加内容模板时，上传素材01、上传素材02
        if(!empty($temp_img_video_files = $request->file($temp_img_video))){

            $temp_img_video_str = '';

            foreach ($temp_img_video_files as $key=>$vfile){

                $key=$key+1;

                if($vfile->isValid()){
                    $img_path = $vfile->store('huace/text/temp/'.$temp_img_video.'/'.date('Y').'-'.date('m').'-'.date('d'));

                    $imgRes = self::addOssUploadImg($client,$mainId,$vfile, $img_path);

                    if($imgRes['code'] ==1) return $imgRes;

                    $temp_img_video_str .=$imgRes['data'].',';
                }else{
                    return ['code' => 1,'msg' => '第'.$key.'图片/视频上传失败','data' => ''];
                }
            }
            $data[$temp_img_video] = substr($temp_img_video_str,0,strrpos($temp_img_video_str,","));

        }elseif(!empty($request->input($temp_img_video))){

            $data[$temp_img_video] = $request->input($temp_img_video);
        }

        if(!empty($fdata['info'][$temp_img_video])){
            //更换素材时，删除服务器中没有用的素材图片
            if(!empty($fdata['old_path'])){

                //删除oss里的文件
                self::delOssFilePath($fdata['old_path'], $client, $mainId);
                unset($fdata);
                return ['code' => 0,'msg'  => 'success','data' => $data];

            }else{
            //修改文字画册内容时，删除服务器中没有用的素材图片
            $temp_img_video_arr2 = explode(',', $data[$temp_img_video]);

            $temp_img_video_arr1 = explode(',', $fdata['info'][$temp_img_video]);

            foreach ($temp_img_video_arr1 as $ivkey=>$ivval){

                if(!in_array($ivval, $temp_img_video_arr2)){

                    //删除oss里的文件
                    self::delOssFilePath($ivval, $client, $mainId);
                }
             }
           }
        }
        $fdata = array_merge($fdata,$data);
        return ['code' => 0,'msg'  => 'success','data' => $fdata];
    }

    /**
     * 修改上传素材的图片视频函数
     */
    static public function updUploadTempImageVideo($client,$request,$fdata,$temp_img_video,$mainId){

        $data = [];
        $data[$temp_img_video] = '';
        //添加内容模板时，上传素材01、上传素材02
        if(!empty($temp_img_video_files = $request->$temp_img_video)){

            $temp_img_video_str = '';

            @ksort($temp_img_video_files);
            foreach ($temp_img_video_files as $key=>$vfile){
                $key=$key+1;
                if(is_file($vfile)){
                    $res = self::handlePicFormat($vfile,'pv','第 '.$key.' 个格式有误！');//判断文件格式

                    if(!empty($res)) return $res;

                    if($vfile->isValid()){
                        $img_path = $vfile->store('huace/text/temp/'.$temp_img_video.'/'.date('Y').'-'.date('m').'-'.date('d'));

                        $imgRes = self::addOssUploadImg($client,$mainId,$vfile, $img_path);

                        if($imgRes['code'] ==1) return $imgRes;

                        $temp_img_video_str .=$imgRes['data'].',';
                    }else{
                        return ['code' => 1,'msg' => '第'.$key.'图片/视频上传失败','data' => ''];
                    }
                }else{
                        $temp_img_video_str .=$vfile.',';
                }
            }

            $data[$temp_img_video] = substr($temp_img_video_str,0,strrpos($temp_img_video_str,","));

        }elseif(!empty($request->input($temp_img_video))){

            $data[$temp_img_video] = $request->input($temp_img_video);
        }

        if(!empty($fdata['info'][$temp_img_video])){
            //更换素材时，删除服务器中没有用的素材图片
            if(!empty($fdata['old_path'])){
                //删除oss里的文件
                self::delOssFilePath($fdata['old_path'], $client, $mainId);
                unset($fdata);
                return ['code' => 0,'msg'  => 'success','data' => $data];

            }else{
                //修改文字画册内容时，删除服务器中没有用的素材图片
                $temp_img_video_arr2 = explode(',', $data[$temp_img_video]);

                $temp_img_video_arr1 = explode(',', $fdata['info'][$temp_img_video]);

                foreach ($temp_img_video_arr1 as $ivkey=>$ivval){

                    if(!in_array($ivval, $temp_img_video_arr2)){

                        //删除oss里的文件
                        self::delOssFilePath($ivval, $client, $mainId);
                    }
                }
            }
        }
        $fdata = array_merge($fdata,$data);
        return ['code' => 0,'msg'  => 'success','data' => $fdata];
    }

    /**
     * 图片上传到oss系统
     * @param unknown $client
     * @param unknown $file
     */
    static public function addOssUploadImg($client,$mainId,$file,$path){
        $res = handleUploadFileType($file);
        if(!empty($res)) return $res;
        $size = $file -> getSize();
         $result = saveFileSize(['main_id'=>$mainId], $size,$path);
         if($result['code'] == 1) return $result;
        try {

            $fullPath = '/uploads/'.$path;
            $ossPath  = ltrim($fullPath,'./');
            $path     = public_path().$fullPath;
            $client -> uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);
            @unlink($path);
            $url = config('app.aliyun_oss_bucket_url').$fullPath;
            return ["code"=>0,"msg"=>"success","data"=>$url];

        } catch (\Exception $e) {

            return ["code"=>1,"msg"=>"OSS系统，上传图片失败！","data"=>""];
        }
    }

    /**
     * 添加水印
     * @param unknown $file
     */
    static public function addWatermark($client,$file,$mainId){
        if(empty($file)) return $file;
        $adminInfo = AdminAddendumModel::select('clear_watermark_or_not')->where(['main_id'=>$mainId])->first();

        if($adminInfo['clear_watermark_or_not']==1){

            return $file;
        }else{

                $delPath = strstr($file, 'uploads/');
                $imgInfo = $client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
                if(strpos($imgInfo['content-type'],'image/') !== false){

                    return $file = $file.config('app.aliyun_oss_img_watermark');
                }

                return $file;
        }
    }

    /**
     * 删除oss里的文件
     * @param unknown $file
     * @param unknown $mainId
     */
     static public function delOssFilePath($file,$client,$mainId){
        if(empty($file)) return $file;
        DB::beginTransaction();
        try {
            $delPath = strstr($file, 'uploads/');
            $imgInfo=$client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
            AdminAddendumModel::where(['main_id'=>$mainId])
            ->decrement('file_total_size', $imgInfo['content-length']);
            $client -> deleteObject(config('app.aliyun_oss_bucket'), $delPath);
            DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return "";
            }
    }

     /**
     * 处理图片和视频格式
     */
    static public function handlePicFormat($files,$flag,$msg){

        $pic_video_format = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts,
                            flash,mpeg,mpeg-2,mpeg-4,midi,wmv,asf,asx,rm,rmvb,mp4,3gp,mov,m4v,avi,dat,mkv,flv,vob,
                            bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,
                            ufo,eps,ai,raw,wmf,webp,avif,apng';

        $pic_format       = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp,avif,apng';

        $music_format     = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts';

        $ext = $files->extension();
        $ext = strtolower($ext);

        if($flag == 'm'){

            $pic_video_format_arr = explode(',',$music_format);

        }elseif($flag == 'p'){

            $pic_video_format_arr = explode(',',$pic_format);

        }else{

            $pic_video_format_arr = explode(',',$pic_video_format);
        }

        if (!in_array($ext, $pic_video_format_arr)) {

            return ['code' => 1,'msg' => $msg,'data' => ''];die;
        }
    }
}
